﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace AIC_PN
{
    public partial class FormDanhMucBaoCaoMau6 : System.Web.UI.Page
    {
        private static int FatherID;
        private PrepareDataForTreeViewMau6 DataForTreeViewDM = new PrepareDataForTreeViewMau6();
        private static int MaDM = 0;
        private static int IDDM = 0;
        #region Ham chuc nang

        protected void UpdateDonVi(int ID, string TenDM)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenDM", SqlDbType.NVarChar, ParameterDirection.Input, TenDM));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                string sql = "UPDATE [tblDanhMucBaoCaoMau6] SET [TenDM] = @TenDM" +
                             ",[UpdateDate] = GETDATE(),[UserID] = @UserID WHERE ID = @ID";
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                MyTran.Commit();
                MyCommon.AddMessage(this.Page.Master, "Cập nhật nội dung báo cáo thành công!", MyConst.MessageType.Success);
            }
            catch
            {
                MyTran.Rollback();
                MyCommon.AddMessage(this.Page.Master, "Cập nhật nội dung báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected void ThemMoiDonVi(int MaDonVi, string TenDonVi, int FatherID, string ParentID, int UserID)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@MaDM", SqlDbType.Int, ParameterDirection.Input, MaDonVi));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenDM", SqlDbType.NVarChar, ParameterDirection.Input, TenDonVi));
                arrParams.Add(SqlHelper.CreateParameterObject("@FatherID", SqlDbType.Int, ParameterDirection.Input, FatherID));
                arrParams.Add(SqlHelper.CreateParameterObject("@ParentID", SqlDbType.NVarChar, ParameterDirection.Input, ParentID));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));

                string sql = "INSERT INTO dbo.tblDanhMucBaoCaoMau6(" +
                             "MaDM,TenDM,FatherID,ParentID,CreateDate,UpdateDate,UserID) " +
                             "VALUES (@MaDM,@TenDM,@FatherID,@ParentID,GETDATE(),GETDATE(),@UserID) " +
                             "DECLARE @ParentIDString NVARCHAR(50) " +
                             "SET @ParentIDString = (SELECT ParentID FROM dbo.tblDanhMucBaoCaoMau6 WHERE ID = @FatherID) " +
                             "UPDATE dbo.tblDanhMucBaoCaoMau6 SET ParentID = @ParentIDString + CONVERT(VARCHAR(5),IDENT_CURRENT('dbo.tblDanhMucBaoCaoMau6')) + ';' " +
                             "WHERE ID = IDENT_CURRENT('dbo.tblDanhMucBaoCaoMau6')";
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                MyTran.Commit();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo thành công !", MyConst.MessageType.Success);
            }
            catch
            {
                MyTran.Rollback();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected void ThemMoiOneDonVi(int MaDonVi, string TenDonVi, int UserID)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@MaDM", SqlDbType.Int, ParameterDirection.Input, MaDonVi));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenDM", SqlDbType.NVarChar, ParameterDirection.Input, TenDonVi));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));

                string sql = "DECLARE @FatherID NVARCHAR(10)" +
                             "SET @FatherID = IDENT_CURRENT('dbo.tblDanhMucBaoCaoMau6') + 1" +
                             "INSERT INTO dbo.tblDanhMucBaoCaoMau6(" +
                             "MaDM,TenDM,FatherID,ParentID,CreateDate,UpdateDate,UserID) " +
                             "VALUES (@MaDM,@TenDM,@FatherID,@FatherID+';',GETDATE(),GETDATE(),@UserID) ";
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                MyTran.Commit();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo thành công !", MyConst.MessageType.Success);
            }
            catch
            {
                MyTran.Rollback();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected DataTable GetChiTietDonVi(int IDDonVi)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, IDDonVi));
            return SqlHelper.ExecuteDataTable(CommandType.Text, "Select * from tblDanhMucBaoCaoMau6 where ID = @ID", arrParams);
        }

        protected DataTable XoaDonVi(int IDDonVi)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, IDDonVi));
            return SqlHelper.ExecuteDataTable(CommandType.Text, "DELETE FROM tblDanhMucBaoCaoMau6 where ID = @ID", arrParams);
        }

        protected void BindDataToTreeView()
        {
            trvDonVi.Nodes.Clear();
            DataForTreeViewDM.PopulateRootLevel(trvDonVi, 0);
            trvDonVi.ExpandAll();
        }

        /// <summary>
        /// Thủ tục kiểm tra quyền sử dụng của người dùng có được quyền truy cập vào mục này hay không?
        /// </summary>
        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("DanhMucBaoCao");
            if (Role == null || Role["Xem"] == 0)
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }
        #endregion Ham chuc nang

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            BindDataToTreeView();
            int UserID = Convert.ToInt32(Session["userid"]);
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("index.aspx");
        }

        protected void trvDonVi_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {
            DataForTreeViewDM.PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
        }

        protected void trvDonVi_SelectedNodeChanged(object sender, EventArgs e)
        {
            btnThemMoi.Visible = true;
            IDDM = Convert.ToInt32(trvDonVi.SelectedValue);
            DataTable ThongTinDonVi = GetChiTietDonVi(IDDM);
            txtTenDoiTuong.Text = ThongTinDonVi.Rows[0]["TenDM"].ToString();
            FatherID = Convert.ToInt32(ThongTinDonVi.Rows[0]["FatherID"]);

            btnLuu.CommandName = MyConst.Action.Update;
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                int UserID = Convert.ToInt32(Session["userid"]);
                if (btnLuu.CommandName == MyConst.Action.Update)
                {
                    UpdateDonVi(IDDM, txtTenDoiTuong.Text);
                    BindDataToTreeView();
                }
                else if (btnLuu.CommandName == MyConst.Action.Addnew)
                {

                    ThemMoiDonVi(MaDM, txtTenDoiTuong.Text, FatherID, "", UserID);
                    BindDataToTreeView();
                }
                else if (btnLuu.CommandName == MyConst.Action.AddOnenew)
                {
                    ThemMoiOneDonVi(MaDM, txtTenDoiTuong.Text, UserID);
                    BindDataToTreeView();
                }
            }
            catch (Exception)
            {
                MyCommon.AddMessage(this.Page.Master, "Có lỗi xảy ra trong quá trình thao tác !", MyConst.MessageType.Error);
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            txtTenDoiTuong.Text = "";
        }

        protected void btnXoa_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode CurentNode = trvDonVi.SelectedNode;
                if (CurentNode.ChildNodes.Count > 0)
                {
                    MyCommon.AddMessage(this.Page.Master, "Không thể xóa nội dung cấp cha !", MyConst.MessageType.Warning);
                }
                else
                {
                    XoaDonVi(Convert.ToInt32(CurentNode.Value));
                    MyCommon.AddMessage(this.Page.Master, "Xóa nội dung báo cáo thành công !", MyConst.MessageType.Success);
                    BindDataToTreeView();
                }
            }
            catch (Exception)
            {
                MyCommon.AddMessage(this.Page.Master, "Có lỗi xảy ra trong quá trình thao tác !", MyConst.MessageType.Error);
            }
        }

        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            btnLuu.CommandName = MyConst.Action.Addnew;
            txtTenDoiTuong.Text = "";
        }

        protected void btnThemMoiMot_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            btnLuu.CommandName = MyConst.Action.AddOnenew;
            txtTenDoiTuong.Text = "";
        }




    }
}
